package com.dotstone.chipism.activity;

import java.io.IOException;
import java.lang.reflect.Field;
import java.util.Hashtable;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.http.RequestParams;

import com.dotstone.chipism.R;
import com.dotstone.chipism.bean.HttpURL;
import com.dotstone.chipism.dialog.SVProgressHUD;
import com.dotstone.chipism.qrcode.BeepManager;
import com.dotstone.chipism.qrcode.CameraManager;
import com.dotstone.chipism.qrcode.CaptureActivityHandler;
import com.dotstone.chipism.qrcode.DecodeThread;
import com.dotstone.chipism.qrcode.InactivityTimer;
import com.dotstone.chipism.util.DeviceManager;
import com.dotstone.chipism.util.QRCodeContentManager;
import com.dotstone.chipism.util.SPUtils;
import com.dotstone.chipism.util.ToastShow;
import com.dotstone.chipism.view.slidingfragmenu.BarUtils;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import com.umeng.analytics.MobclickAgent;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Rect;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.TranslateAnimation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/*************************************************************************
 * 公 司： 深圳市高金科技有限公司 作 者： 深圳市高金科技有限公司 文件名称：CaptureActivity.java 内容摘要：第三方扫描二维码框架
 * 不需多做改动 日 期： 2016-11-28
 ************************************************************************/
public final class CaptureActivity extends Activity implements
		SurfaceHolder.Callback {

	private static final String TAG = "Tag";
	private CameraManager cameraManager;
	private CaptureActivityHandler handler;
	private InactivityTimer inactivityTimer;
	private BeepManager beepManager;
	private SurfaceView scanPreview = null;
	private RelativeLayout scanContainer;
	private RelativeLayout scanCropView;
	private ImageView scanLine;
	private LinearLayout mBackL;
	private Button mAddHandB;
	private Rect mCropRect = null;
	private boolean isHasSurface = false;
	private TextView tv_statusBar_mian;
	private int entry; // 入口 1 、从首次安装过来 2、从主界面扫一扫过来 3、从注册见面过来
	private SVProgressHUD mSVProgressHUD;
	private boolean success = false;
	public Handler getHandler() {
		return handler;
	}

	public CameraManager getCameraManager() {
		return cameraManager;
	}

	@Override
	public void onCreate(Bundle icicle) {
		super.onCreate(icicle);

		Window window = getWindow();
		window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
		setContentView(R.layout.activity_capture);
		scanPreview = (SurfaceView) findViewById(R.id.capture_preview);
		scanContainer = (RelativeLayout) findViewById(R.id.capture_container);
		scanCropView = (RelativeLayout) findViewById(R.id.capture_crop_view);
		scanLine = (ImageView) findViewById(R.id.capture_scan_line);
		mBackL = (LinearLayout) findViewById(R.id.back_layout);
		mAddHandB = (Button) findViewById(R.id.add_btn);
		tv_statusBar_mian = (TextView) findViewById(R.id.tv_statusBar_mian);
		inactivityTimer = new InactivityTimer(this);
		beepManager = new BeepManager(this);
		entry = getIntent().getIntExtra("entry", 0);
		if (entry == 3) {
			mAddHandB.setVisibility(View.GONE);
		}
		TranslateAnimation animation = new TranslateAnimation(
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.0f,
				Animation.RELATIVE_TO_PARENT, 0.9f);
		animation.setDuration(4500);
		animation.setRepeatCount(-1);
		animation.setRepeatMode(Animation.RESTART);
		scanLine.startAnimation(animation);
		initEvent();
		boolVersion();
	}

	public void boolVersion() {
		if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {

			Window window = getWindow();
			window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
					WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
			// 透明导航栏
			// getWindow().addFlags(
			// WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
			// 改变titlebar的高度
			int statusbarHeight = BarUtils.getStatusBarHeight(this);
			RelativeLayout.LayoutParams layoutParams1 = (RelativeLayout.LayoutParams) tv_statusBar_mian
					.getLayoutParams();
			layoutParams1.height = statusbarHeight;
			tv_statusBar_mian.setLayoutParams(layoutParams1);
			tv_statusBar_mian.setVisibility(View.VISIBLE);

		} else {
			tv_statusBar_mian.setVisibility(View.GONE);
		}
	}

	@Override
	protected void onResume() {
		super.onResume();
		MobclickAgent.onResume(this);
		cameraManager = new CameraManager(getApplication());
		handler = null;
		if (isHasSurface) {
			initCamera(scanPreview.getHolder());
		} else {
			scanPreview.getHolder().addCallback(this);
		}

		inactivityTimer.onResume();
		// 检查超时 如果10秒还没有扫到东西 就直接返回
		checkTimeOut(20);
	}

	Handler mHandler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 0:
				if(success){
					return;
				}
				ToastShow.Show(getApplicationContext(), "没有扫描到结果");
				finish();
				break;

			default:
				break;
			}
		}
	};
	
	

	private void checkTimeOut(int time) {
		mHandler.postDelayed(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				Message msg = Message.obtain();
				msg.what = 0;
				mHandler.sendMessage(msg);
			}
		}, time * 1000);
	}
	
	@Override
	protected void onPause() {
		MobclickAgent.onPause(this);
		success = true;
		if (handler != null) {
			handler.quitSynchronously();
			handler = null;
		}
		inactivityTimer.onPause();
		beepManager.close();
		cameraManager.closeDriver();
		if (!isHasSurface) {
			scanPreview.getHolder().removeCallback(this);
		}
		super.onPause();
	}

	@Override
	protected void onDestroy() {
		inactivityTimer.shutdown();
		super.onDestroy();
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		if (holder == null) {
			Log.e(TAG, "警告！当前无图像!");
		}
		if (!isHasSurface) {
			isHasSurface = true;
			initCamera(holder);
		}
	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		isHasSurface = false;
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {

	}

	public void handleDecode(Result rawResult, Bundle bundle) {
		inactivityTimer.onActivity();
		beepManager.playBeepSoundAndVibrate();
		String content = rawResult.getText().toString();
		Log.i("wmy", "获取扫描结果 = " + rawResult.getText());

		if (entry == 1) {
			Intent resultIntent = new Intent(CaptureActivity.this,
					FirstSetupActivity1.class);
			bundle.putString("result", rawResult.getText());
			resultIntent.putExtras(bundle);
			success = true;
			resultIntent.putExtra("result", rawResult.getText());
			resultIntent.putExtra("entry", entry);
			startActivity(resultIntent);
			finish();
		} else if (entry == 2) {
			String contents[] = content.split("&");
			if (contents.length < 2) {
				return;
			}
			String url[] = contents[0].split("\\?");
			if (url.length < 2) {
				return;
			}
			String handleTypes[] = url[1].split("=");
			if (Integer.parseInt(handleTypes[1]) == 2) {
				String shareInfoIds[] = contents[1].split("=");
				if (shareInfoIds.length < 2) {
					return;
				}
				String shareInfoId = shareInfoIds[1];
				String userIds[] = contents[2].split("=");
				if (userIds.length < 2) {
					return;
				}
				String userId = userIds[1];
				success = true;
				getShareContent(shareInfoId, userId);
			}
		} else if (entry == 3) {
			String contents[] = content.split("&");
			if (contents.length < 2) {
				return;
			}
			String url[] = contents[0].split("\\?");
			if (url.length < 2) {
				return;
			}
			String handleTypes[] = url[1].split("=");
			if (Integer.parseInt(handleTypes[1]) == 3) {
				String userTypes[] = contents[1].split("=");
				String userType = userTypes[1];
				String phones[] = contents[2].split("=");
				String phone = phones[1];
				String tokens[] = contents[3].split("=");
				String token = tokens[1];
				QRCodeContentManager.getInstance().setUserType(userType);
				QRCodeContentManager.getInstance().setPhone(phone);
				QRCodeContentManager.getInstance().setToken(token);
			}
			success = true;
			finish();
		}
	}

	private void initCamera(SurfaceHolder surfaceHolder) {
		if (surfaceHolder == null) {
			throw new IllegalStateException("No SurfaceHolder provided");
		}
		if (cameraManager.isOpen()) {
			Log.w(TAG,
					"initCamera() while already open -- late SurfaceView callback?");
			return;
		}
		try {
			cameraManager.openDriver(surfaceHolder);
			if (handler == null) {
				handler = new CaptureActivityHandler(this, cameraManager,
						DecodeThread.ALL_MODE);
			}

			initCrop();
		} catch (IOException ioe) {
			Log.w(TAG, ioe);
			displayFrameworkBugMessageAndExit();
		} catch (RuntimeException e) {
			Log.w(TAG, "Unexpected error initializing camera", e);
			displayFrameworkBugMessageAndExit();
		}
	}

	private void displayFrameworkBugMessageAndExit() {
		AlertDialog.Builder builder = new AlertDialog.Builder(this);
		builder.setTitle(getString(R.string.app_name));
		builder.setMessage("Camera error");
		builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {

			@Override
			public void onClick(DialogInterface dialog, int which) {
				finish();
			}

		});
		builder.setOnCancelListener(new DialogInterface.OnCancelListener() {

			@Override
			public void onCancel(DialogInterface dialog) {
				finish();
			}
		});
		builder.show();
	}

	public void restartPreviewAfterDelay(long delayMS) {
		if (handler != null) {
			handler.sendEmptyMessageDelayed(R.id.restart_preview, delayMS);
		}
	}

	public Rect getCropRect() {
		return mCropRect;
	}

	/**
	 * 初始化截取的矩形区域
	 */
	private void initCrop() {
		int cameraWidth = cameraManager.getCameraResolution().y;
		int cameraHeight = cameraManager.getCameraResolution().x;

		/** 获取布局中扫描框的位置信息 */
		int[] location = new int[2];
		scanCropView.getLocationInWindow(location);

		int cropLeft = location[0];
		int cropTop = location[1] - getStatusBarHeight();

		int cropWidth = scanCropView.getWidth();
		int cropHeight = scanCropView.getHeight();

		/** 获取布局容器的宽高 */
		int containerWidth = scanContainer.getWidth();
		int containerHeight = scanContainer.getHeight();

		/** 计算最终截取的矩形的左上角顶点x坐标 */
		int x = cropLeft * cameraWidth / containerWidth;
		/** 计算最终截取的矩形的左上角顶点y坐标 */
		int y = cropTop * cameraHeight / containerHeight;

		/** 计算最终截取的矩形的宽度 */
		int width = cropWidth * cameraWidth / containerWidth;
		/** 计算最终截取的矩形的高度 */
		int height = cropHeight * cameraHeight / containerHeight;

		/** 生成最终的截取的矩形 */
		mCropRect = new Rect(x, y, width + x, height + y);
	}

	private int getStatusBarHeight() {
		try {
			Class<?> c = Class.forName("com.android.internal.R$dimen");
			Object obj = c.newInstance();
			Field field = c.getField("status_bar_height");
			int x = Integer.parseInt(field.get(obj).toString());
			return getResources().getDimensionPixelSize(x);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return 0;
	}

	// ===================================

	// private Button btn_local_image;

	private Bitmap scanBitmap;

	private String photo_path;

	private void initEvent() {
		mBackL.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				finish();
			}
		});
		mAddHandB.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				Intent intent = new Intent();
				switch (entry) {
				case 2:	//来自
					intent = new Intent(CaptureActivity.this,
							AddTypeSelectionActivity.class);
					intent.putExtra("entry", entry);
					break;
				case 1:	//来自首次安装
					intent = new Intent(CaptureActivity.this,
							AddTypeSelectionActivity1.class);
					intent.putExtra("entry", entry);
					break;
				default:
					break;
				}
				startActivity(intent);
				finish();
			}
		});
	}

	/**
	 * 扫描二维码图片的方法
	 * 
	 * @param path
	 * @return
	 */
	public Result scanningImage(String path) {
		if (TextUtils.isEmpty(path)) {
			return null;
		}
		Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
		hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); // 设置二维码内容的编码

		BitmapFactory.Options options = new BitmapFactory.Options();
		options.inJustDecodeBounds = true; // 先获取原大小
		scanBitmap = BitmapFactory.decodeFile(path, options);
		options.inJustDecodeBounds = false; // 获取新的大小
		int sampleSize = (int) (options.outHeight / (float) 200);
		if (sampleSize <= 0)
			sampleSize = 1;
		options.inSampleSize = sampleSize;
		scanBitmap = BitmapFactory.decodeFile(path, options);
		int width = scanBitmap.getWidth();
		int height = scanBitmap.getHeight();
		int[] pixels = new int[width * height];
		scanBitmap.getPixels(pixels, 0, width, 0, 0, width, height);
		/**
		 * 第三个参数是图片的像素
		 */
		RGBLuminanceSource source = new RGBLuminanceSource(width, height,
				pixels);
		BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
		QRCodeReader reader = new QRCodeReader();
		try {
			return reader.decode(bitmap1, hints);

		} catch (NotFoundException e) {
			e.printStackTrace();
		} catch (ChecksumException e) {
			e.printStackTrace();
		} catch (FormatException e) {
			e.printStackTrace();
		}
		return null;
	}

	private void getShareContent(String shareInfoId, String userId) {
		mSVProgressHUD = new SVProgressHUD(CaptureActivity.this);
		mSVProgressHUD.showWithStatus("正在提交");
		RequestParams params = new RequestParams(HttpURL.HANDLE_SHARE_URL);
		params.setAsJsonContent(true);
		JSONObject obj = new JSONObject();
		try {
			obj.put("handelType", 1);
			obj.put("hid", DeviceManager.getInstance().hid);
			obj.put("shareInfoId", shareInfoId);
			obj.put("userId", userId);
			obj.put("key", "10000");
			obj.put("requestTime", "" + System.currentTimeMillis());
			obj.put("token",
					(String) SPUtils.get(getApplicationContext(), "token", ""));

			Log.d("Tag", " upload Share = " + obj.toString());
		} catch (JSONException e1) {
			e1.printStackTrace();
		}
		params.setBodyContent(obj.toString());
		x.http().post(params, new Callback.CommonCallback<String>() {
			
			@Override
			public void onSuccess(String result) {
				Log.i("wmy", "获取分享"+result);
				try {
					JSONObject jo = new JSONObject(result);
					String resultCode = jo.getString("resultCode");
					if (resultCode.equals("1")) {
						// 上传成功，保存到本地
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "已获取分享！");
						finish();
					} else {
						if (mSVProgressHUD.isShowing()) {
							mSVProgressHUD.dismiss();
						}
						ToastShow.Show(getApplicationContext(), "获取分享失败！");
						finish();
					}
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			}

			@Override
			public void onCancelled(CancelledException arg0) {

			}

			@Override
			public void onError(Throwable arg0, boolean arg1) {
				ToastShow.Show(getApplicationContext(), "网络错误！");
			}

			@Override
			public void onFinished() {

			}

		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (resultCode == RESULT_OK) {
			switch (requestCode) {
			case 0x01:
				// 获取选中图片的路径
				Cursor cursor = getContentResolver().query(data.getData(),
						null, null, null, null);
				if (cursor.moveToFirst()) {
					photo_path = cursor.getString(cursor
							.getColumnIndex(MediaStore.Images.Media.DATA));
				}
				cursor.close();

				new Thread(new Runnable() {
					@Override
					public void run() {
						Result result = scanningImage(photo_path);
						if (result != null) {
							handleDecode(result, new Bundle());
						}
					}
				}).start();

				break;

			}
		}
	}
}